﻿using RuoVea.GoFastdfs.Dto;
using RuoVea.GoFastdfs.Entity;
using RuoVea.GoFastdfs.Entity.Context;
using RuoVea.GoFastdfs.Service.Inserface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RuoVea.GoFastdfs.Service
{
    /// <summary>
    /// 集群表, 逻辑处理
    /// </summary>
    public class RuoveadService: IRuoveadService
    {
        RuoVeaContext _context;
        public RuoveadService(RuoVeaContext context)
        {
            _context = context;
        }


        public PageResult<RuoveadEntiy> listPage(int page, int limit)
        {
            PageResult<RuoveadEntiy> result = new PageResult<RuoveadEntiy>();
            if (page <= 0) page = 1;

           var query = _context.RuoveadEntiys;
           var pageInfo = query.Skip((page-1)*limit).Take(page*limit);

            result.total = query.Count(); ;
            result.state = 200;
            result.data = pageInfo.ToList();

            return result;
        }

        /// <summary>
        /// 检查集群是否已存在
        /// </summary>
        /// <param name="serverAddress"></param>
        /// <returns></returns>
        public Boolean checkRuovead(String serverAddress)
        {
            return _context.RuoveadEntiys.Any(x => x.ServerAddress.Equals(serverAddress));
        }

        /// <summary>
        /// 新增集群
        /// </summary>
        /// <param name="peers"></param>
        /// <returns></returns>
        public Boolean addRuovead(RuoveadEntiy ruovead)
        {
            try
            {
                ruovead.createTime = DateTime.Now;
                _context.RuoveadEntiys.Add(ruovead);
                _context.SaveChanges();
                return true;
            }
            catch { return false; }
        }

        /// <summary>
        /// 根据id删除集群
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Boolean delRuoveadById(int id)
        {
            try
            {
                RuoveadEntiy  peers = new RuoveadEntiy() { Id = 8 };
                //将要删除的对象附加到EF容器中
                _context.RuoveadEntiys.Attach(peers);
                //Remove()起到了标记当前对象为删除状态，可以删除
                _context.RuoveadEntiys.Remove(peers);
                _context.SaveChanges();
                return true;
            }
            catch { return false; }
        }

        public RuoveadEntiy getById(int id)
        {
          return _context.RuoveadEntiys.Where(x => x.Id == id).FirstOrDefault();
        }

        public List<RuoveadEntiy> list()
        {
          return  _context.RuoveadEntiys.ToList();
        }
    }
}
